package com.yami.shop.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yami.shop.bean.dto.BlogSwitchDTO;
import com.yami.shop.bean.dto.UserSearchBlogDTO;
import com.yami.shop.bean.enums.EsOperationType;
import com.yami.shop.bean.enums.InteractPowerEnum;
import com.yami.shop.bean.event.EsHotWordsUpdateEvent;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.vo.BlogPersonVO;
import com.yami.shop.bean.vo.BlogUserVO;
import com.yami.shop.bean.vo.BlogVO;
import com.yami.shop.bean.vo.MyFriendVo;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.enums.ECommentType;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.IPHelper;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.personnft.common.service.PersonShareService;
import com.yami.shop.search.common.service.EsHotWordsService;
import com.yami.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 功能描述: 广场
 * @Author: LSR
 * @Date: 2022/12/28 10:00
 */

@RestController
@RequestMapping("/api/blog")
public class BlogController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private BlogSortService blogSortService;
    @Autowired
    private TagService tagService;
    @Autowired
    private UserService userService;
    @Autowired
    private FriendService friendService;
    @Autowired
    private ShopDetailService shopDetailService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserCollectionDtcService userCollectionDtcService;
    @Autowired
    private UserSecurityConfigService userSecurityConfigService;
    @Autowired
    private UserBrowseHistoryService userBrowseHistoryService;
    @Autowired
    private UserSearchHistoryService userSearchHistoryService;
    @Autowired
    private UserBlockService userBlockService;
    @Autowired
    private ReportService reportService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private MeltCloudGroupService groupService;
    @Autowired
    private MeltCloudUserService meltCloudUserService;
    @Autowired
    private EsHotWordsService esHotWordsService;
    @Autowired
    private MeltCloudUserRemarkService userRemarkService;
    @Autowired
    private ApplicationEventPublisher eventPublisher;
    @Autowired
    private PersonShareService personShareService;
    private static final String HOT_COMMENT_RULE = "HOT_COMMENT_RULE";  // 热评规则，点赞超过设定数就为热评，默认点赞数为10
    private static final String HOT_COMMENT_NUM = "HOT_COMMENT_NUM";  // 热评条数，前端展示多少条热评数，默认展示数为1

    @GetMapping("/detail")
    @Operation(summary =  "详情", description = "根据参数分页获取平台品牌列表")
    @Parameter(name = "uid", description = "博客id", required = true)
    public ServerResponseEntity<Blog> detail(Long uid,String userUid) {
        Blog byId = blogService.getById(uid);
        if(byId.getArticleSource() ==1){//用户
            User userByUserId = userService.getUserByUserId(byId.getUserUid());
            String name = userByUserId.getNickName();
            if (StringUtils.isNotEmpty(userUid)) {
                MeltCloudUserRemark one = userRemarkService.getOne(Wrappers.lambdaQuery(MeltCloudUserRemark.class).eq(MeltCloudUserRemark::getUserId, userUid).eq(MeltCloudUserRemark::getType, 1).eq(MeltCloudUserRemark::getObjId, byId.getUserUid()));
                if (one != null && StringUtils.isNotEmpty(one.getRemark())) {
                    name = one.getRemark();
                }
            }
            byId.setUserName(name);
            byId.setUserPic(userByUserId.getPic());
            byId.setIsHasRealName(CharSequenceUtil.isNotEmpty(userByUserId.getRealName()));
            byId.setProvince(ObjectUtil.isNull(byId.getIp())? IPHelper.getIpProvinceAddr(userByUserId.getUserRegip()): IPHelper.getIpProvinceAddr(byId.getIp()));
        }else if(byId.getArticleSource() ==2){
            byId.setUserName("DTC++");
        }else if(byId.getArticleSource() ==3){
            ShopDetail shopDetail = shopDetailService.getById(byId.getShopId());
            byId.setUserName(shopDetail.getShopName());
            byId.setUserPic(shopDetail.getShopLogo());
        }
        if (StringUtils.isNotEmpty(userUid)) {
            LambdaQueryWrapper<UserBlock> eq = Wrappers.lambdaQuery(UserBlock.class).select(UserBlock::getBlockUserId).eq(UserBlock::getUserId, userUid);
            List<String> blockUserIds = userBlockService.listObjs(eq, ub -> ub.toString());
            //过滤自己举报的评论数
            LambdaQueryWrapper<Report> wrapper = new LambdaQueryWrapper<Report>().select(Report::getReportObjId).eq(Report::getStatus, 0).eq(Report::getReportType, 1).eq(Report::getUserId, userUid);
            List<Long> uidIds = reportService.listObjs(wrapper, o -> Long.valueOf(o.toString()));
            LambdaQueryWrapper<Comment> wrapper1 = Wrappers.lambdaQuery(Comment.class)
                    .eq(Comment::getStatus, 1).eq(Comment::getType, 0).isNull(Comment::getToUid).eq(Comment::getBlogUid, uid)
                    .notIn(CollUtil.isNotEmpty(blockUserIds),Comment::getUserUid, blockUserIds)
                    .notIn(CollUtil.isNotEmpty(uidIds),Comment::getUid, uidIds);
            List<Comment> ones = commentService.list(wrapper1);
            byId.setCommentCount(ones.size());
        }
        //判断是否自己点过赞
        if(CharSequenceUtil.isNotEmpty(userUid)){
            QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("blog_uid", uid);
            queryWrapper.eq("source", "1");
            queryWrapper.eq("user_uid",userUid);
            queryWrapper.isNull("to_uid");
            queryWrapper.eq("type",1);
            queryWrapper.eq("status", 1);
            // 查询出该文章下所有的评论
            List<Comment> pageList = commentService.list(queryWrapper);
            byId.setPraiseIsMe(pageList.size()>0?true:false);
            //判断是否收藏
            LambdaQueryWrapper<UserCollectionDtc> eq = new LambdaQueryWrapper<UserCollectionDtc>()
                    .eq(UserCollectionDtc::getUserId, userUid)
                    .eq(UserCollectionDtc::getCollectionType, 2)
                    .eq(UserCollectionDtc::getProdId, uid);
            long count = userCollectionDtcService.count(eq);
            byId.setCollectionIsMe(count>0?true:false);
        }
        byId.setIsShow("1".equals(byId.getIsPublish())&&byId.getStatus()==1);

        if(CharSequenceUtil.isNotEmpty(userUid) && byId.getStatus() == 1){
            // 保存浏览记录
            List<UserBrowseHistory> list = userBrowseHistoryService.list(Wrappers.lambdaQuery(UserBrowseHistory.class).eq(UserBrowseHistory::getUserId, userUid).eq(UserBrowseHistory::getHistoryType, "1").eq(UserBrowseHistory::getBlogId, uid));
            if(list.isEmpty()){
                UserBrowseHistory userBrowseHistory = new UserBrowseHistory();
                userBrowseHistory.setUserId(userUid);
                userBrowseHistory.setHistoryType("1");
                userBrowseHistory.setBlogId(uid);
                userBrowseHistory.setCreateTime(new Date());
                userBrowseHistoryService.save(userBrowseHistory);
            }
        }

        return ServerResponseEntity.success(byId);
    }

    @GetMapping("/pagePerson")
    @Operation(summary =  "个人动态", description = "根据参数分页获取平台品牌列表")
    public ServerResponseEntity<IPage<Blog>> pagePerson(PageParam<Blog> page, BlogVO blog,String cruserId) {
        if(CharSequenceUtil.isBlank(blog.getUserUid())){
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        blogLambdaQueryWrapper.eq(Blog::getUserUid, blog.getUserUid());
        String[] split = blog.getType().split(",");
        blogLambdaQueryWrapper.in(Blog::getType, split);//圈子
        blogLambdaQueryWrapper.eq(Blog::getIsPublish,"1");
        if (blog.getUserUid().equals(cruserId)) {
            blogLambdaQueryWrapper.in(Blog::getStatus, 1,3);
        } else {
            blogLambdaQueryWrapper.eq(Blog::getStatus, 1);//审核通过
        }
        //过滤被举报的
        LambdaQueryWrapper<Report> wrapper = new LambdaQueryWrapper<Report>().select(Report::getReportObjId).eq(Report::getReportType, 0).eq(Report::getUserId, cruserId);
        List<Long> objIds = reportService.listObjs(wrapper, o -> Long.valueOf(o.toString()));
        blogLambdaQueryWrapper.notIn(CollUtil.isNotEmpty(objIds),Blog::getUid, objIds);
        blogLambdaQueryWrapper.orderByDesc(Blog::getCreateTime);
        IPage<Blog> brandList = blogService.page(page, blogLambdaQueryWrapper);
        //判断是否点赞过
        List<Long> blogIds = brandList.getRecords().stream().map(Blog::getUid).collect(Collectors.toList());
        List<Long> fanalBlogIds = null;
        Map<Long, List<Comment>> mapCommentCount = null;
        List<Long> collect = null;
        if(!blogIds.isEmpty() && CharSequenceUtil.isNotEmpty(cruserId)){
            QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("blog_uid", blogIds);
            queryWrapper.eq("source", "1");
            queryWrapper.eq("user_uid",cruserId);
            queryWrapper.isNull("to_uid");
            queryWrapper.eq("type",1);
            queryWrapper.eq("status", 1);
            // 查询出该文章下所有的评论
            List<Comment> pageList = commentService.list(queryWrapper);
            fanalBlogIds = pageList.stream().map(Comment::getBlogUid).collect(Collectors.toList());
            LambdaQueryWrapper<UserBlock> eq = Wrappers.lambdaQuery(UserBlock.class).select(UserBlock::getBlockUserId).eq(UserBlock::getUserId, cruserId);
            List<String> blockUserIds = userBlockService.listObjs(eq, Object::toString);
            //过滤自己举报的评论数
            LambdaQueryWrapper<Report> wrappe = new LambdaQueryWrapper<Report>().select(Report::getReportObjId).eq(Report::getStatus, 0).eq(Report::getReportType, 1).eq(Report::getUserId, cruserId);
            List<Long> uidIds = reportService.listObjs(wrappe, o -> Long.valueOf(o.toString()));
            LambdaQueryWrapper<Comment> wrapper1 = Wrappers.lambdaQuery(Comment.class)
                    .eq(Comment::getStatus, 1).eq(Comment::getType, 0).isNull(Comment::getToUid).in(Comment::getBlogUid, blogIds)
                    .notIn(CollUtil.isNotEmpty(blockUserIds),Comment::getUserUid, blockUserIds)
                    .notIn(CollUtil.isNotEmpty(uidIds),Comment::getUid, uidIds);
            List<Comment> list = commentService.list(wrapper1);
            mapCommentCount = list.stream().collect(Collectors.groupingBy(Comment::getBlogUid));
            //获取收藏
            LambdaQueryWrapper<UserCollectionDtc> eq1 = new LambdaQueryWrapper<UserCollectionDtc>()
                    .eq(UserCollectionDtc::getUserId, cruserId)
                    .eq(UserCollectionDtc::getCollectionType, "2")
                    .in(UserCollectionDtc::getProdId, blogIds);
            List<UserCollectionDtc> list1 = userCollectionDtcService.list(eq1);
            collect = list1.stream().map(UserCollectionDtc::getProdId).collect(Collectors.toList());
        }
        User userByUserId = userService.getUserByUserId(blog.getUserUid());
        String name = userByUserId.getNickName();
        if (CharSequenceUtil.isNotEmpty(cruserId)) {
            MeltCloudUserRemark one = userRemarkService.getOne(Wrappers.lambdaQuery(MeltCloudUserRemark.class).eq(MeltCloudUserRemark::getUserId, cruserId).eq(MeltCloudUserRemark::getType, 1).eq(MeltCloudUserRemark::getObjId, blog.getUserUid()));
            if (Objects.nonNull(one) && CharSequenceUtil.isNotEmpty(one.getRemark())) {
                name = one.getRemark();
            }
        }
        List<Long> finalFanalBlogIds = fanalBlogIds;
        Map<Long, List<Comment>> finalMapCommentCount = mapCommentCount;
        List<Long> finalCollect = collect;
        String finalName = name;
        brandList.getRecords().forEach(blog1 ->{
            if (finalMapCommentCount != null) {
                blog1.setCommentCount(finalMapCommentCount.get(blog1.getUid()) == null ? 0 : finalMapCommentCount.get(blog1.getUid()).size());
            }
            blog1.setUserName(finalName);
            blog1.setUserPic(userByUserId.getPic());
            blog1.setIsHasRealName(CharSequenceUtil.isNotEmpty(userByUserId.getRealName()));
            if(finalFanalBlogIds!=null&& !finalFanalBlogIds.isEmpty()){
                //判断是否点赞过
                blog1.setPraiseIsMe(finalFanalBlogIds.contains(blog1.getUid()));
            }
            if(finalCollect !=null&& !finalCollect.isEmpty()){
                //判断是否点赞过
                blog1.setCollectionIsMe(finalCollect.contains(blog1.getUid()));
            }
        });
        return ServerResponseEntity.success(brandList);
    }

    @GetMapping("/page")
    @Operation(summary =  "朋友圈", description = "根据参数分页获取平台品牌列表")
    public ServerResponseEntity<IPage<Blog>> page(PageParam<Blog> page, BlogVO blog) {
        if(CharSequenceUtil.isBlank(blog.getUserUid())){
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        String userUid = blog.getUserUid();
        User userByUserId = userService.getUserByUserId(userUid);
        if(userByUserId==null){
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        return ServerResponseEntity.success(pageSelectCircleBlog(page, blog));
    }

    @GetMapping("/pageBlog")
    @Operation(summary =  "广场", description = "根据参数分页获取平台品牌列表")
    public ServerResponseEntity<IPage<Blog>> pageBlog(PageParam<Blog> page,BlogVO blog,String currentId) {
        blog.setType("0");
        return ServerResponseEntity.success(pageSelectPlazaBlog(page, blog, currentId, null));
    }


    @PostMapping
    @Operation(summary =  "新增朋友圈和广场信息", description = "新增广场信息")
    public ServerResponseEntity<Void> saveTag(@RequestBody BlogUserVO blogUserVO){
        User userByUserId = userService.getUserByUserId(blogUserVO.getUserId());
        if(userByUserId==null){
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }

        String id = IdUtil.getSnowflake().nextIdStr();
        if (blogUserVO.getIsblog() == 0) {
            createBlog(id, userByUserId, blogUserVO, 0); //博客
        } else if (blogUserVO.getIsblog() == 2 || blogUserVO.getIsblog() == 4) {
            createBlog(id, userByUserId, blogUserVO, blogUserVO.getIsblog()); //圈子
        } else {
            createBlog(id, userByUserId, blogUserVO, 0); //博客
            createBlog(id, userByUserId, blogUserVO, 2); //圈子
        }
        return ServerResponseEntity.success();
    }

    /**
     *  创建博客
     *
     * @param id
     * @param userByUserId
     * @param blogUserVO
     * @param type
     */
    private void createBlog(String id, User userByUserId, BlogUserVO blogUserVO, Integer type) {
        BlogSwitchDTO blogSwitchDTO = sysConfigService.getSysConfigObject(Constant.BLOG_SWITCH_CONFIG, BlogSwitchDTO.class);
        Integer auditType = 0;
        if (type.equals(0) && Objects.nonNull(blogSwitchDTO) && blogSwitchDTO.getSquareAudit()) {
            auditType = 1;
        } else if (type.equals(2) && Objects.nonNull(blogSwitchDTO) && blogSwitchDTO.getCircleAudit()) {
            auditType = 1;
        } else if (type.equals(4) && Objects.nonNull(blogSwitchDTO) && blogSwitchDTO.getCircleAudit()) {
            auditType = 1;
        }
        Blog blog = new Blog();
        blog.setStatus(3);//待审核
        blog.setAuditType(auditType);
        blog.setIsOriginal("1");//原创
        blog.setAuthor(userByUserId.getNickName());
        blog.setLevel(0);
        blog.setIsPublish("1");
        blog.setOpenComment(1);
        UserSecurityConfig securityConfig = userSecurityConfigService.getByUserId(userByUserId.getUserId());
        if (Objects.nonNull(securityConfig) && Objects.nonNull(securityConfig.getComment())) {
            blog.setOpenComment(securityConfig.getComment());
        }
        blog.setType(type);
        blog.setUserUid(userByUserId.getUserId());
        blog.setContent(blogUserVO.getContent());
        blog.setArticleSource(1);
        blog.setTitleImg(blogUserVO.getTitleImg());
        blog.setTitle(id);//作为和圈子管理的值
        blog.setCreateTime(new Date());
        blog.setIp(IPHelper.getIpAddr());
        blogService.saveData(blog);
    }


    @PostMapping("/comment/manage")
    @Operation(summary =  "博客评论管理", description = "博客评论管理")
    public ServerResponseEntity commentManage(@RequestBody Blog blogParam) {
        if (Objects.isNull(blogParam.getUid()) || Objects.isNull(blogParam.getOpenComment()) || com.yami.shop.common.util.StringUtils.isEmpty(blogParam.getUserUid())) {
            throw new YamiShopBindException( "yami.sys.illegalArgument");
        }
        Blog blog = blogService.getById(blogParam.getUid());
        if (!blog.getUserUid().equals(blogParam.getUserUid())) {
            throw new YamiShopBindException("yami.no.auth");
        }
        if (!blog.getOpenComment().equals(blogParam.getOpenComment())) {
            InteractPowerEnum instance = InteractPowerEnum.instance(blogParam.getOpenComment());
            if (Objects.isNull(instance)) {
                throw new YamiShopBindException("yami.dtc.blog.manage.error");
            }
            blogService.updateById(blogParam);
        }
        return ServerResponseEntity.success();
    }


    /**
     * allDel false 删除博客获取圈子 true 全删  （博客的品类及子评论，及点赞同理）
     * @param uid
     * @param userId
     * @param allDel
     * @return
     */
    @GetMapping("/delUserBlog")
    @Operation(summary =  "删除", description = "修改广场信息")
    public ServerResponseEntity<Void> delUserBlog(Long uid,String userId,Boolean allDel){
        Blog blog = blogService.getById(uid);
        if(!blog.getUserUid().equals(userId)){
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.dtc.blog.del.check"));
        }
        List<Blog> listBlog = new ArrayList<>();

        //查询是否有博客和圈子
        if(allDel){
            LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
            blogLambdaQueryWrapper.in(Blog::getStatus, 1,3);
            blogLambdaQueryWrapper.eq(Blog::getUserUid,userId);
            blogLambdaQueryWrapper.eq(Blog::getTitle,blog.getTitle());
            listBlog = blogService.list(blogLambdaQueryWrapper);
        }else{
            listBlog.add(blog);
        }

        List<Long> ids = new ArrayList<>();
        listBlog.forEach(item -> {
            ids.add(item.getUid());
        });
        //获取文章的点赞和评论及子点赞和评论
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getStatus,1);//审核通过
        wrapper.in(Comment::getBlogUid,ids);
        List<Comment> listAll = commentService.list(wrapper);
        //获取文章的点赞和评论
        LambdaQueryWrapper<Comment> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.isNull(Comment::getToUid);
        wrapper1.eq(Comment::getStatus,1);//审核通过
        wrapper1.in(Comment::getBlogUid,ids);
        List<Comment> list1 = commentService.list(wrapper1);
        Map<Integer, Long> collect = list1.stream().collect(Collectors.groupingBy(Comment::getType, Collectors.counting()));
        listBlog.forEach(item -> {
            item.setStatus(0);
            item.setUpdateTime(new Date());
            long l1 = ObjectUtil.isNull(collect.get(ECommentType.PRAISE)) ? 0 : collect.get(ECommentType.PRAISE);
            item.setClickCount(item.getClickCount()>=(int) l1? item.getClickCount()-(int) l1 :0);
            long l2 = ObjectUtil.isNull(collect.get(ECommentType.COMMENT)) ? 0 : collect.get(ECommentType.COMMENT);
            item.setCommentCount(item.getCommentCount()>=(int)l2?item.getCommentCount()-(int) l2:0);
        });
        listAll.forEach(item -> {
            item.setStatus(0);
            item.setUpdateTime(new Date());
        });
        commentService.updateBatchById(listAll);//删除所有评论和点赞
        blogService.updateBatchById(listBlog);//删除博客和圈子
        userBrowseHistoryService.remove(Wrappers.lambdaQuery(UserBrowseHistory.class)
                .eq(UserBrowseHistory::getHistoryType,1).in(UserBrowseHistory::getBlogId,ids));// 删除历史记录表
        return ServerResponseEntity.success();
    }

    @GetMapping("/pagePersonCollect")
    @Operation(summary =  "个人收藏", description = "根据参数分页获取个人收藏列表")
    public ServerResponseEntity<IPage<Blog>> pagePersonCollect(PageParam<Blog> page,BlogVO blog,String currentId) {

        IPage<Blog> brandList = new Page<>(page.getCurrent(),page.getSize());
        if (StringUtils.isBlank(currentId)) {
            return ServerResponseEntity.success(brandList);
        }
        brandList = userCollectionDtcService.pageUserBrowseHistory(page, currentId, blog.getContent());
        plazaBlogCommon(brandList, currentId);

        return ServerResponseEntity.success(brandList);
    }

    @GetMapping("/pagePersonPraise")
    @Operation(summary =  "个人点赞", description = "根据参数分页获取个人点赞列表")
    public ServerResponseEntity<IPage<Blog>> pagePersonPraise(PageParam<Blog> page,BlogVO blog,String currentId) {

        IPage<Blog> brandList = new Page<>(page.getCurrent(),page.getSize());
        if (StringUtils.isBlank(currentId)) {
            return ServerResponseEntity.success(brandList);
        }
        brandList = commentService.pagePraiseUserBrowseHistory(page, currentId, blog.getContent());
        plazaBlogCommon(brandList, currentId);
        return ServerResponseEntity.success(brandList);
    }

    @GetMapping("/pagePersonBuyShareWorks")
    @Operation(summary =  "个人购买记录", description = "根据参数分页获取个人点赞列表")
    public ServerResponseEntity<IPage<Blog>> pagePersonBuyShareWorks(PageParam<Blog> page,BlogVO blog,String currentId) {
        IPage<Blog> brandList = new Page<>(page.getCurrent(),page.getSize());
        if (StringUtils.isBlank(currentId)) {
            return ServerResponseEntity.success(brandList);
        }
        List<Long> blogIds = personShareService.getBuyReceiveOutIdList(currentId);
        brandList = pageSelectPlazaBlog(page,blog,currentId,blogIds);
        plazaBlogCommon(brandList, currentId);
        return ServerResponseEntity.success(brandList);
    }

    @GetMapping("/pagePersonComment")
    @Operation(summary =  "个人评论", description = "根据参数分页获取个人评论列表")
    public ServerResponseEntity<IPage<Comment>> pagePersonComment(PageParam<Comment> page,BlogVO blog,String currentId) {

        IPage<Comment> commentList = null;
        if (StringUtils.isBlank(currentId)) {
            commentList = new Page<>(page.getCurrent(),page.getSize());
            return ServerResponseEntity.success(commentList);
        }

        LambdaQueryWrapper<Comment> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        blogLambdaQueryWrapper.eq(Comment::getType, 0);//评论
        if(ObjectUtil.isNotEmpty(blog.getContent())){
            blogLambdaQueryWrapper.like(Comment::getContent,blog.getContent());
        }
        blogLambdaQueryWrapper.eq(Comment::getStatus,1);//未删除
        blogLambdaQueryWrapper.isNull(Comment::getToUid);//发布
        blogLambdaQueryWrapper.eq(Comment::getUserUid, currentId); // 个人收藏微博id
        blogLambdaQueryWrapper.orderByDesc(Comment::getCreateTime).orderByDesc(Comment::getUid);

        // 查询出所有个人评论微博id
        commentList = commentService.page(page, blogLambdaQueryWrapper);

        if (CollectionUtils.isEmpty(commentList.getRecords())) {
            commentList = new Page<>(page.getCurrent(),page.getSize());
            return ServerResponseEntity.success(commentList);
        }

        String sysHotComment = sysConfigService.getValue(HOT_COMMENT_RULE);
        String sysHotCommentNum = sysConfigService.getValue(HOT_COMMENT_NUM);
        Integer hotRule = StringUtils.isBlank(sysHotComment) ? 10 : Integer.parseInt(sysHotComment);
        Integer hotLimit = StringUtils.isBlank(sysHotCommentNum) ? 1 : Integer.parseInt(sysHotCommentNum);
        LambdaQueryWrapper<UserBlock> eq = Wrappers.lambdaQuery(UserBlock.class).select(UserBlock::getBlockUserId).eq(UserBlock::getUserId, currentId);
        List<String> blockUserIds = userBlockService.listObjs(eq, ub -> ub.toString());
        List<MeltCloudUserRemark> remarkList = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class).eq(MeltCloudUserRemark::getUserId, currentId).eq(MeltCloudUserRemark::getType, 1));
        Map<String, String> remarkMap = remarkList.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));
        commentList.getRecords().forEach(a -> {
            Blog blog1 = blogService.getById(a.getBlogUid());
            blog1.setRelation(0);
            //获取圈子的userid 及用户对象
            String blogUserId = blog1.getUserUid();
            if (blockUserIds.contains(blogUserId)) {
                blog1.setStatus(4);
                a.setBlog(blog1);
                return;
            }
            //替换用户昵称
            if (ObjectUtil.isNotEmpty(blogUserId) && blog1.getArticleSource() == 1) {
                User user = userService.getUserByUserId(blogUserId);
                if (null != user) {
                    blog1.setAuthor(user.getNickName());
                    String name = StringUtils.isNotEmpty(remarkMap.get(blogUserId)) ? remarkMap.get(blogUserId) : user.getNickName();
                    blog1.setUserName(name);
                    blog1.setUserPic(user.getPic());
                    blog1.setIsHasRealName(CharSequenceUtil.isNotEmpty(user.getRealName()));
                }
                Map<String, UserSecurityConfig> configMap = new HashMap<>();
                Map<String, MyFriendVo> userRelations = new HashMap<>();
                if(CharSequenceUtil.isNotBlank(currentId) && user != null){
                    List<String> ids = new ArrayList<>();
                    ids.add(user.getUserId());
                    List<UserSecurityConfig> listConfig = userSecurityConfigService.list(new LambdaQueryWrapper<UserSecurityConfig>().in(UserSecurityConfig::getUserId, ids));
                    configMap = listConfig.stream().collect(Collectors.toMap(UserSecurityConfig::getUserId, Function.identity()));
                    List<MyFriendVo> relations = friendService.getRelations(ids, currentId);
                    userRelations = relations.stream().collect(Collectors.toMap(MyFriendVo::getId, Function.identity()));
                    //添加是否对自己开通私聊
                    UserSecurityConfig userSecurityConfig = configMap.get(user.getUserId());
                    MyFriendVo myFriendVo = userRelations.get(user.getUserId());
                    if(ObjectUtil.isNotNull(userSecurityConfig)&&ObjectUtil.isNotNull(myFriendVo)){
                        blog1.setIsHasRealName(myFriendVo.getIsHasRealName());
                        blog1.setMassageSwitch(friendService.getPrivacyTypeValue(Integer.valueOf(myFriendVo.getStatus()),userSecurityConfig.getPrivacyType()));
                        blog1.setRelation(Integer.parseInt(myFriendVo.getStatus()));
                    }
                }
            }

            // 获取分类信息
            Long blogSortIds = blog1.getBlogSortUid();
            if(ObjectUtil.isNotEmpty(blogSortIds)){
                BlogSort blogSorts = blogSortService.getById(blogSortIds);
                blog1.setBlogSort(blogSorts);
            }

            // 获取标签信息
            String tagIds = blog1.getTagUid();
            if(ObjectUtil.isNotEmpty(tagIds)){
                List<String> tagIdAlls = new ArrayList<>();
                if(tagIds.contains(",")){
                    String[] split = tagIds.split(",");
                    tagIdAlls.addAll(Arrays.asList(split)) ;
                }else if(CharSequenceUtil.isNotEmpty(tagIds)){
                    tagIdAlls.add(tagIds);
                }
                tagIdAlls = tagIdAlls.stream().distinct().collect(Collectors.toList());
                List<Tag> tags = tagService.listByIds(tagIdAlls);
                blog1.setTagList(tags);
            }

            //获取博客id集合
            Long praiseNum = commentService.count(Wrappers.lambdaQuery(Comment.class).eq(Comment::getBlogUid, blog1.getUid()).eq(Comment::getType, 1)
                    .eq(Comment::getStatus, 1).isNull(Comment::getToUid));
            long praise = commentService.count(Wrappers.lambdaQuery(Comment.class).eq(Comment::getBlogUid, blog1.getUid()).eq(Comment::getType, 1)
                    .eq(Comment::getStatus, 1).isNull(Comment::getToUid).eq(Comment::getUserUid, currentId));
            long collection = userCollectionDtcService.count(Wrappers.lambdaQuery(UserCollectionDtc.class).eq(UserCollectionDtc::getCollectionType, 2)
                    .eq(UserCollectionDtc::getUserId, currentId).eq(UserCollectionDtc::getProdId, blog1.getUid()));

            List<Comment> comments = commentService.getHotComment(blog1.getUid(), currentId, hotLimit, hotRule);

            Boolean praiseIsMe = praise > 0 ? true : false;
            Boolean collectionIsMe = collection > 0 ? true : false;
            Integer praiseIsMeNum = praiseNum.intValue();
            List<Comment> hotComment = comments == null ? new ArrayList<>() : comments;

            // 获取点赞状态
            blog1.setPraiseIsMe(praiseIsMe);
            // 获取收藏状态
            blog1.setCollectionIsMe(collectionIsMe);
            // 获取点赞数量
            blog1.setPraiseIsMeNum(praiseIsMeNum);
            // 获取热评数据
            blog1.setHotComment(hotComment);

            a.setBlog(blog1);

        });

        return ServerResponseEntity.success(commentList);
    }

    @GetMapping("/pagePersonHistory")
    @Operation(summary =  "个人浏览历史", description = "根据参数分页获取个人浏览历史列表")
    public ServerResponseEntity<IPage<Blog>> pagePersonHistory(PageParam<Blog> page,BlogVO blog,String currentId) {

        IPage<Blog> brandList = new Page<>(page.getCurrent(),page.getSize());
        if (StringUtils.isBlank(currentId)) {
            return ServerResponseEntity.success(brandList);
        }
        brandList = userBrowseHistoryService.pageUserBrowseHistory(page, currentId, blog.getContent());
        plazaBlogCommon(brandList, currentId);
        return ServerResponseEntity.success(brandList);
    }

    @PostMapping("/deletePerson")
    @Operation(summary =  "删除个人记录", description = "根据参数删除个人收藏、评论、点赞、历史")
    public ServerResponseEntity<Boolean> deletePerson(@RequestBody BlogPersonVO vo) {

        if (vo.getCurrentId() == null || ((vo.getIsClear() == null || !vo.getIsClear()) && CollectionUtils.isEmpty(vo.getIds()))) {
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        switch (vo.getType()) {
            case 1 : //收藏
                userCollectionDtcService.deteleByUserIdAndProdId(vo.getCurrentId(), "2", vo.getIds());
                break;
            case 2 : //评论
                List<Comment> commentList = new ArrayList<>();
                if (vo.getIsClear() != null && vo.getIsClear()) {
                    commentList = commentService.list(Wrappers.lambdaQuery(Comment.class).eq(Comment::getType,"0")
                            .eq(Comment::getStatus,1).isNull(Comment::getToUid).eq(Comment::getUserUid, vo.getCurrentId()));
                } else {
                    commentList = commentService.list(Wrappers.lambdaQuery(Comment.class).eq(Comment::getType,"0")
                            .eq(Comment::getStatus,1).isNull(Comment::getToUid).eq(Comment::getUserUid, vo.getCurrentId()).in(Comment::getUid, vo.getIds()));
                }
                commentList.forEach(a -> {
                    blogService.addAndCancelCommentCount(a.getBlogUid(), false);
                });
                commentService.deteleByUserIdAndProdId(vo.getCurrentId(), "0", vo.getIds());
                break;
            case 3 : //点赞
                List<Long> blogIdList = new ArrayList<>();
                if (vo.getIsClear() != null && vo.getIsClear()) {
                    List<Comment> praiseList = commentService.list(Wrappers.lambdaQuery(Comment.class).eq(Comment::getType,"1")
                            .eq(Comment::getStatus,1).isNull(Comment::getToUid).eq(Comment::getUserUid, vo.getCurrentId()));
                    blogIdList = praiseList.stream().map(a -> a.getBlogUid()).collect(Collectors.toList());
                } else {
                    blogIdList = vo.getIds();
                }
                blogIdList.forEach(a -> {
                    blogService.addAndCancelPraiseCount(a, false);
                });
                commentService.deteleByUserIdAndProdId(vo.getCurrentId(), "1", vo.getIds());
                break;
            case 4 : //历史
                userBrowseHistoryService.deteleByUserIdAndProdId(vo.getCurrentId(), "1", vo.getIds());
                break;
            default:
                throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        return ServerResponseEntity.success(true);
    }

    @GetMapping("/searchAllListPage")
    @Operation(summary =  "通过类型搜索信息", description = "通过类型搜索信息")
    public ServerResponseEntity<IPage> searchUserListPage(PageParam page, UserSearchBlogDTO dto){

        String currentId = dto.getCurrentId();
        if (StringUtils.isBlank(currentId)) {
            currentId = null;
        }
        String content = dto.getContent().trim();
        Integer type = dto.getType();
        String source = dto.getSource();

        if (type == null) {
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        IPage iPage = new Page<>(page.getCurrent(),page.getSize());
        BlogVO blog = new BlogVO();
        blog.setContent(content);
        blog.setUserUid(currentId);
        switch (type) {
            case 0 : //广场
                blog.setType("0");
                iPage = pageSelectPlazaBlog(page, blog, currentId, null);
                break;
            case 1 : //圈子
                iPage = pageSelectCircleBlog(page, blog);
                break;
            case 2 : //用户
                iPage = friendService.searchUserListPage(page, currentId, content);
                List<MyFriendVo> records = iPage.getRecords();
                if(ObjectUtil.isNull(records) || records.size()==0){
                    break;
                }
                List<String> userids = records.stream().map(s -> s.getId()).collect(Collectors.toList());
                List<UserSecurityConfig> list = userSecurityConfigService.list(new LambdaQueryWrapper<UserSecurityConfig>().in(UserSecurityConfig::getUserId, userids));
                Map<String, UserSecurityConfig> userMap = list.stream().collect(Collectors.toMap(UserSecurityConfig::getUserId, Function.identity()));
                records.stream().forEach(myFriendVo->{//添加是否对自己开通私聊
                    UserSecurityConfig userSecurityConfig = userMap.get(myFriendVo.getId());
                    myFriendVo.setMassageSwitch(friendService.getPrivacyTypeValue(Integer.valueOf(myFriendVo.getStatus()),userSecurityConfig.getPrivacyType()));
                });
                break;
            case 3 : //群聊
                iPage = groupService.searchGroupListPage(page, currentId, content);
                List<MeltCloudGroup> groups = iPage.getRecords();
                groups.forEach(meltCloudGroup -> {
                    List<MeltCloudUser> users = meltCloudUserService.getGroupsUser(meltCloudGroup.getId());
                    meltCloudGroup.setUsers(users);
                });
                break;
            default:
                throw new YamiShopBindException("yami.sys.illegalArgument");
        }

        //记录查询日志，只有用户登录的时候才会记录
        if (StringUtils.isNotBlank(currentId) && StringUtils.isNotBlank(content)) {
            if (StringUtils.isBlank(source)) {
                source = "00";
            }
            List<UserSearchHistory> list = userSearchHistoryService.list(Wrappers.lambdaQuery(UserSearchHistory.class).eq(UserSearchHistory::getUserId,currentId)
                    .eq(UserSearchHistory::getSource, source).orderByDesc(UserSearchHistory::getCreateTime).last(" limit 1 "));
            if (ObjectUtil.isEmpty(list) || !list.get(0).getContent().equals(content)) {
                UserSearchHistory history = new UserSearchHistory();
                history.setUserId(currentId);
                history.setSource(source);
                history.setContent(content);
                history.setCreateTime(new Date());
                userSearchHistoryService.save(history);
                eventPublisher.publishEvent(new EsHotWordsUpdateEvent(history.getHistoryId(), EsOperationType.SAVE));
            }
        }

        return ServerResponseEntity.success(iPage);
    }

    @GetMapping("/searchHistoryRecordList")
    @Operation(summary =  "搜索值历史记录信息", description = "搜索值历史记录信息")
    public ServerResponseEntity<List<UserSearchHistory>> searchHistoryRecordList(@RequestParam String currentId, String source){

        List<UserSearchHistory> list = new ArrayList<>();
        if (StringUtils.isBlank(currentId)) {
            return ServerResponseEntity.success(list);
        }
        if (StringUtils.isBlank(source)) {
            source = "00";
        }
        list = userSearchHistoryService.list(Wrappers.lambdaQuery(UserSearchHistory.class).eq(UserSearchHistory::getUserId,currentId)
                .eq(UserSearchHistory::getSource, source).orderByDesc(UserSearchHistory::getCreateTime).last(" limit 10 "));
        return ServerResponseEntity.success(list);
    }

    @GetMapping("/deleteSearchHistoryRecord")
    @Operation(summary =  "搜索值历史记录信息", description = "搜索值历史记录信息")
    public ServerResponseEntity<Boolean> deleteSearchHistoryRecord(@RequestParam String currentId, String source){
        if (StringUtils.isBlank(currentId)) {
            return ServerResponseEntity.success(true);
        }
        if (StringUtils.isBlank(source)) {
            source = "00";
        }
        List<UserSearchHistory> list = userSearchHistoryService.list(Wrappers.lambdaQuery(UserSearchHistory.class)
                .eq(UserSearchHistory::getUserId,currentId).eq(UserSearchHistory::getSource, source));
        List<Long> ids = list.stream().map(s -> s.getHistoryId()).collect(Collectors.toList());
        userSearchHistoryService.removeBatchByIds(list);
        esHotWordsService.deleteBatch(ids);
        return ServerResponseEntity.success(true);
    }

    /**
     *  查询圈子公共方法
     *
     * @param page
     * @param blog
     */
    private IPage<Blog> pageSelectCircleBlog(PageParam<Blog> page, BlogVO blog) {

        List<MyFriendVo> myFriendVoIPage = friendService.followPageNoPage(blog.getUserUid());//关注列表
        List<String> collect = myFriendVoIPage.stream().map(MyFriendVo::getId).collect(Collectors.toList());
        collect.add(blog.getUserUid());
        List<User> users = userService.listByIds(collect);
        Map<String, User> userMap = users.stream().collect(Collectors.toMap(User::getUserId, Function.identity()));
        LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        blogLambdaQueryWrapper.in(Blog::getType, 2,4);//圈子

        if (StringUtils.isNotEmpty(blog.getUserUid())) {
            blogLambdaQueryWrapper.and(wp ->
                    wp.and(wp1 -> wp1.in(Blog::getUserUid, collect).eq(Blog::getStatus, 1))
                            .or(wp2 -> wp2.eq(Blog::getUserUid, blog.getUserUid()).eq(Blog::getStatus, 3)));
            //过滤被举报的
            LambdaQueryWrapper<Report> wrapper = new LambdaQueryWrapper<Report>().select(Report::getReportObjId).eq(Report::getReportSou, 1).eq(Report::getReportType, 0).eq(Report::getUserId, blog.getUserUid());
            List<Long> objIds = reportService.listObjs(wrapper, o -> Long.valueOf(o.toString()));
            if (CollUtil.isNotEmpty(objIds)) {
                blogLambdaQueryWrapper.notIn(Blog::getUid, objIds);
            }
        } else {
            blogLambdaQueryWrapper.in(Blog::getUserUid, collect);//所以关注用户uid集合和自己的id
            blogLambdaQueryWrapper.eq(Blog::getStatus, 1);//审核通过
        }
        if(ObjectUtil.isNotEmpty(blog.getContent())) {
            blogLambdaQueryWrapper.like(Blog::getContent,blog.getContent());
        }
        blogLambdaQueryWrapper.orderByDesc(Blog::getCreateTime);
        IPage<Blog> brandList = blogService.page(page, blogLambdaQueryWrapper);
        Map<String, UserSecurityConfig> configMap = new HashMap<>();
        Map<String, MyFriendVo> userRelations = new HashMap<>();
        //判断是否点赞过
        List<Long> blogIds = brandList.getRecords().stream().map(Blog::getUid).collect(Collectors.toList());
        //获取博客id集合
        Map<Long, Boolean> praiseIsMeMap = new HashMap<>(); //点赞集合
        Map<Long, Boolean> collectionIsMeMap = new HashMap<>(); //收藏集合
        Map<Long, Integer> praiseIsMeNumMap = new HashMap<>(); //点赞数集合
        Map<Long, List<Comment>> hotCommentMap = new HashMap<>(); //热评集合

        if(blogIds.size()>0){
            //获取用户和自己关系 确定私信是否开通
            List<String> ids = brandList.getRecords().stream().map(Blog::getUserUid).distinct().collect(Collectors.toList());
            List<UserSecurityConfig> listConfig = userSecurityConfigService.list(new LambdaQueryWrapper<UserSecurityConfig>().in(UserSecurityConfig::getUserId, ids));
            configMap = listConfig.stream().collect(Collectors.toMap(UserSecurityConfig::getUserId, Function.identity()));
            List<MyFriendVo> relations = friendService.getRelations(ids, blog.getUserUid());
            userRelations = relations.stream().collect(Collectors.toMap(MyFriendVo::getId, Function.identity()));

            String sysHotComment = sysConfigService.getValue(HOT_COMMENT_RULE);
            String sysHotCommentNum = sysConfigService.getValue(HOT_COMMENT_NUM);
            Integer hotRule = StringUtils.isBlank(sysHotComment) ? 10 : Integer.parseInt(sysHotComment);
            Integer hotLimit = StringUtils.isBlank(sysHotCommentNum) ? 1 : Integer.parseInt(sysHotCommentNum);

            blogIds.forEach(a ->{
                Long praiseNum = commentService.count(Wrappers.lambdaQuery(Comment.class).eq(Comment::getBlogUid, a).eq(Comment::getType, 1)
                        .eq(Comment::getStatus, 1).isNull(Comment::getToUid));
                List<Comment> comments = commentService.getHotComment(a, blog.getUserUid(), hotLimit, hotRule);

                if (StringUtils.isNotBlank(blog.getUserUid())) {
                    long praise = commentService.count(Wrappers.lambdaQuery(Comment.class).eq(Comment::getBlogUid, a).eq(Comment::getType, 1)
                            .eq(Comment::getStatus, 1).isNull(Comment::getToUid).eq(Comment::getUserUid, blog.getUserUid()));
                    long collection = userCollectionDtcService.count(Wrappers.lambdaQuery(UserCollectionDtc.class).eq(UserCollectionDtc::getCollectionType, 2)
                            .eq(UserCollectionDtc::getUserId, blog.getUserUid()).eq(UserCollectionDtc::getProdId, a));
                    Boolean praiseIsMe = praise > 0;
                    Boolean collectionIsMe = collection > 0;
                    praiseIsMeMap.put(a, praiseIsMe);
                    collectionIsMeMap.put(a, collectionIsMe);
                }
                Integer praiseIsMeNum = praiseNum.intValue();
                List<Comment> hotComment = comments == null ? new ArrayList<>() : comments;
                praiseIsMeNumMap.put(a, praiseIsMeNum);
                hotCommentMap.put(a, hotComment);
            });
        } else {
            return brandList;
        }

        List<MeltCloudUserRemark> remarkList = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class).eq(MeltCloudUserRemark::getUserId, blog.getUserUid()).eq(MeltCloudUserRemark::getType, 1).in(MeltCloudUserRemark::getObjId, collect));
        Map<String, String> remarkMap = remarkList.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));
        Map<String, UserSecurityConfig> finalConfigMap = configMap;
        Map<String, MyFriendVo> finalUserRelations = userRelations;
        Map<Long, List<Comment>> mapCommentCount = null;
        if (StringUtils.isNotEmpty(blog.getUserUid())) {
            LambdaQueryWrapper<UserBlock> eq = Wrappers.lambdaQuery(UserBlock.class).select(UserBlock::getBlockUserId).eq(UserBlock::getUserId, blog.getUserUid());
            List<String> blockUserIds = userBlockService.listObjs(eq, Object::toString);
            if (CollUtil.isNotEmpty(blockUserIds)) {
                LambdaQueryWrapper<Comment> wrapper = Wrappers.lambdaQuery(Comment.class)
                        .eq(Comment::getStatus, 1).eq(Comment::getType, 0).isNull(Comment::getToUid).in(Comment::getBlogUid, blogIds)
                        .notIn(Comment::getUserUid, blockUserIds);
                List<Comment> list = commentService.list(wrapper);
                mapCommentCount = list.stream().collect(Collectors.groupingBy(Comment::getBlogUid));
            }
        }
        Map<Long, List<Comment>> finalMapCommentCount = mapCommentCount;
        brandList.getRecords().forEach(blog1 ->{
            if (finalMapCommentCount != null) {
                blog1.setCommentCount(finalMapCommentCount.get(blog1.getUid()) == null ? 0 : finalMapCommentCount.get(blog1.getUid()).size());
            }
            blog1.setRelation(0);
            User user = userMap.get(blog1.getUserUid());
            if(user!=null){
                String name = StringUtils.isEmpty(remarkMap.get(blog1.getUserUid())) ? user.getNickName() : remarkMap.get(blog1.getUserUid());
                blog1.setUserName(name);
                blog1.setUserPic(user.getPic());
                blog1.setIsHasRealName(CharSequenceUtil.isNotEmpty(user.getRealName()));
                //添加是否对自己开通私聊
                UserSecurityConfig userSecurityConfig = finalConfigMap.get(blog1.getUserUid());
                MyFriendVo myFriendVo = finalUserRelations.get(blog1.getUserUid());
                if(ObjectUtil.isNotNull(userSecurityConfig)&&ObjectUtil.isNotNull(myFriendVo)){
                    blog1.setMassageSwitch(friendService.getPrivacyTypeValue(Integer.valueOf(myFriendVo.getStatus()),userSecurityConfig.getPrivacyType()));
                    blog1.setIsHasRealName(myFriendVo.getIsHasRealName());
                    blog1.setRelation(Integer.parseInt(myFriendVo.getStatus()));
                }
            }
            if (StringUtils.isNotBlank(blog1.getUserUid())) {
                // 获取点赞状态
                blog1.setPraiseIsMe(praiseIsMeMap.get(blog1.getUid()));
                // 获取收藏状态
                blog1.setCollectionIsMe(collectionIsMeMap.get(blog1.getUid()));
            }
            // 获取点赞数量
            blog1.setPraiseIsMeNum(praiseIsMeNumMap.get(blog1.getUid()));
            // 获取热评数据
            blog1.setHotComment(hotCommentMap.get(blog1.getUid()));
        });

        return brandList;
    }

    /**
     *  查询广场公共方法
     *
     * @param page
     * @param blog
     * @param currentId
     * @param uids
     * @return
     */
    private IPage<Blog> pageSelectPlazaBlog(PageParam<Blog> page,BlogVO blog,String currentId, List<Long> uids) {

        LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(ObjectUtil.isNotEmpty(blog.getType())){
            blogLambdaQueryWrapper.eq(Blog::getType,blog.getType());
        }
        blogLambdaQueryWrapper.eq(Blog::getIsPublish,1);//发布

        if (CharSequenceUtil.isNotBlank(currentId)) {
            blogLambdaQueryWrapper.and(wp -> wp.eq(Blog::getStatus, 1).or(wp2 -> wp2.eq(Blog::getUserUid, currentId).eq(Blog::getStatus, 3)));

            //过滤被举报的
            LambdaQueryWrapper<Report> wrapper = new LambdaQueryWrapper<Report>().select(Report::getReportObjId).eq(Report::getReportSou, 0).eq(Report::getReportType, 0).eq(Report::getUserId, currentId);
            List<Long> objIds = reportService.listObjs(wrapper, o -> Long.valueOf(o.toString()));
            if (CollUtil.isNotEmpty(objIds)) {
                blogLambdaQueryWrapper.notIn(Blog::getUid, objIds);
            }
            //过滤被拉黑的
            LambdaQueryWrapper<UserBlock> eq = Wrappers.lambdaQuery(UserBlock.class).select(UserBlock::getBlockUserId).eq(UserBlock::getUserId, currentId);
            List<String> blockUserIds = userBlockService.listObjs(eq, ub -> ub.toString());
            if (CollUtil.isNotEmpty(blockUserIds)) {
                blogLambdaQueryWrapper.notIn(Blog::getUserUid, blockUserIds);
            }
        } else {
            blogLambdaQueryWrapper.eq(Blog::getStatus,1);//审核通过
        }

        //可以根据分类和标签搜素特定博客
        if(ObjectUtil.isNotEmpty(blog.getBlogSortUid())){
            blogLambdaQueryWrapper.eq(Blog::getBlogSortUid,blog.getBlogSortUid());
        }
        if(ObjectUtil.isNotEmpty(blog.getTagUid())){
            blogLambdaQueryWrapper.in(Blog::getTagUid,blog.getTagUid());
        }

        if(ObjectUtil.isNotEmpty(blog.getContent())){
            blogLambdaQueryWrapper.like(Blog::getContent,blog.getContent());
        }
        if(ObjectUtil.isNotEmpty(uids)){
            blogLambdaQueryWrapper.in(Blog::getUid, uids); // 个人收藏微博id
        }

        blogLambdaQueryWrapper.orderByDesc(Blog::getLevel).orderByDesc(Blog::getCreateTime);
        IPage<Blog> brandList = blogService.page(page, blogLambdaQueryWrapper);
        plazaBlogCommon(brandList, currentId);

        return brandList;
    }

    /**
     *  博客公共处理
     *
     * @param brandList
     * @param currentId
     */
    private void plazaBlogCommon(IPage<Blog> brandList, String currentId) {
        if (CollUtil.isEmpty(brandList.getRecords())) {
            return;
        }
        //获取圈子的userid 及用户对象
        List<String> blogUserIds = brandList.getRecords().stream().filter(blog1 -> ObjectUtil.isNotEmpty(blog1.getUserUid())&&blog1.getArticleSource()==1).map(Blog::getUserUid).collect(Collectors.toList());
        Collection<User> userList = new ArrayList<>();
        Map<String, String> remarkMap = new HashMap<>();
        if (blogUserIds.size() > 0) {
            userList = userService.listByIds(blogUserIds);
            if (StringUtils.isNotEmpty(currentId)) {
                List<MeltCloudUserRemark> remarkList = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class).eq(MeltCloudUserRemark::getUserId, currentId).eq(MeltCloudUserRemark::getType, 1).in(MeltCloudUserRemark::getObjId, blogUserIds));
                remarkMap = remarkList.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));
            }
        }
        List<User> filterUserListTo = userList.stream().distinct().collect(Collectors.toList());
        Map<String, User> userMap = filterUserListTo.stream().collect(Collectors.toMap(User::getUserId, Function.identity()));
        // 获取分类信息
        List<Long> blogSortIds = brandList.getRecords().stream().filter(blog1 -> ObjectUtil.isNotEmpty(blog1.getBlogSortUid())).map(Blog::getBlogSortUid).collect(Collectors.toList());
        List<BlogSort> blogSorts = new ArrayList<>();
        if(ObjectUtil.isNotEmpty(blogSortIds)){
            blogSorts = blogSortService.listByIds(blogSortIds);
        }
        Map<Long, BlogSort> blogSortMap = blogSorts.stream().collect(Collectors.toMap(BlogSort::getUid, Function.identity()));
        // 获取标签信息
        List<String> tagIds = brandList.getRecords().stream().filter(blog1 -> CharSequenceUtil.isNotEmpty(blog1.getTagUid())).map(Blog::getTagUid).collect(Collectors.toList());
        List<String> tagIdAlls = new ArrayList<>();
        List<Tag> tags = new ArrayList<>();
        if(ObjectUtil.isNotEmpty(tagIds)){
            tagIds.forEach(s->{
                if(s.contains(",")){
                    String[] split = s.split(",");
                    tagIdAlls.addAll(Arrays.asList(split)) ;
                }else if(CharSequenceUtil.isNotEmpty(s)){
                    tagIdAlls.add(s);
                }
            });
            tagIds = tagIdAlls.stream().distinct().collect(Collectors.toList());
            tags = tagService.listByIds(tagIds);
        }
        Map<Long, Tag> tagsMap = tags.stream().collect(Collectors.toMap(Tag::getUid, Function.identity()));
        Map<String, UserSecurityConfig> configMap = new HashMap<>();
        Map<String, MyFriendVo> userRelations = new HashMap<>();
        //获取用户和自己关系 确定私信是否开通
        if(CharSequenceUtil.isNotBlank(currentId)&& !filterUserListTo.isEmpty()){
            List<String> ids = filterUserListTo.stream().map(User::getUserId).collect(Collectors.toList());
            List<UserSecurityConfig> listConfig = userSecurityConfigService.list(new LambdaQueryWrapper<UserSecurityConfig>().in(UserSecurityConfig::getUserId, ids));
            configMap = listConfig.stream().collect(Collectors.toMap(UserSecurityConfig::getUserId, Function.identity()));
            List<MyFriendVo> relations = friendService.getRelations(ids, currentId);
            userRelations = relations.stream().collect(Collectors.toMap(MyFriendVo::getId, Function.identity()));
        }

        //获取博客id集合
        List<Long> blogIds = brandList.getRecords().stream().map(Blog::getUid).collect(Collectors.toList());
        Map<Long, Boolean> praiseIsMeMap = new HashMap<>(); //点赞集合
        Map<Long, Boolean> collectionIsMeMap = new HashMap<>(); //收藏集合
        Map<Long, Integer> praiseIsMeNumMap = new HashMap<>(); //点赞数集合
        Map<Long, List<Comment>> hotCommentMap = new HashMap<>(); //热评集合

        String sysHotComment = sysConfigService.getValue(HOT_COMMENT_RULE);
        String sysHotCommentNum = sysConfigService.getValue(HOT_COMMENT_NUM);
        Integer hotRule = StringUtils.isBlank(sysHotComment) ? 10 : Integer.parseInt(sysHotComment);
        Integer hotLimit = StringUtils.isBlank(sysHotCommentNum) ? 1 : Integer.parseInt(sysHotCommentNum);

        blogIds.forEach(a ->{
            Long praiseNum = commentService.count(Wrappers.lambdaQuery(Comment.class).eq(Comment::getBlogUid, a).eq(Comment::getType, 1)
                    .eq(Comment::getStatus, 1).isNull(Comment::getToUid));
            List<Comment> comments = commentService.getHotComment(a, currentId, hotLimit, hotRule);

            if (StringUtils.isNotBlank(currentId)) {
                long praise = commentService.count(Wrappers.lambdaQuery(Comment.class).eq(Comment::getBlogUid, a).eq(Comment::getType, 1)
                        .eq(Comment::getStatus, 1).isNull(Comment::getToUid).eq(Comment::getUserUid, currentId));
                long collection = userCollectionDtcService.count(Wrappers.lambdaQuery(UserCollectionDtc.class).eq(UserCollectionDtc::getCollectionType, 2)
                        .eq(UserCollectionDtc::getUserId, currentId).eq(UserCollectionDtc::getProdId, a));
                Boolean praiseIsMe = praise > 0 ? true : false;
                Boolean collectionIsMe = collection > 0 ? true : false;
                praiseIsMeMap.put(a, praiseIsMe);
                collectionIsMeMap.put(a, collectionIsMe);
            }
            Integer praiseIsMeNum = praiseNum.intValue();
            List<Comment> hotComment = comments == null ? new ArrayList<>() : comments;
            praiseIsMeNumMap.put(a, praiseIsMeNum);
            hotCommentMap.put(a, hotComment);
        });

        Map<String, UserSecurityConfig> finalConfigMap = configMap;
        Map<String, MyFriendVo> finalUserRelations = userRelations;
        //评论数计算
        List<String> blockUserIds = null;
        List<Long> uidIds = null;
        if (StringUtils.isNotEmpty(currentId)) {//拉黑的
            LambdaQueryWrapper<UserBlock> eq = Wrappers.lambdaQuery(UserBlock.class).select(UserBlock::getBlockUserId).eq(UserBlock::getUserId, currentId);
            blockUserIds = userBlockService.listObjs(eq, ub -> ub.toString());
            //过滤自己举报的评论数
            LambdaQueryWrapper<Report> wrapper = new LambdaQueryWrapper<Report>().select(Report::getReportObjId).eq(Report::getStatus, 0).eq(Report::getReportType, 1).eq(Report::getUserId, currentId);
            uidIds = reportService.listObjs(wrapper, o -> Long.valueOf(o.toString()));
        }
        LambdaQueryWrapper<Comment> wrapper = Wrappers.lambdaQuery(Comment.class)
                .eq(Comment::getStatus, 1).eq(Comment::getType, 0).isNull(Comment::getToUid).in(Comment::getBlogUid, blogIds)
                .notIn(CollUtil.isNotEmpty(blockUserIds),Comment::getUserUid, blockUserIds)
                .notIn(CollUtil.isNotEmpty(uidIds),Comment::getUid, uidIds);
        List<Comment> list = commentService.list(wrapper);
        Map<Long, List<Comment>> finalMapCommentCount = list.stream().collect(Collectors.groupingBy(Comment::getBlogUid));
        Map<String, String> finalRemarkMap = remarkMap;
        brandList.getRecords().forEach(item->{
            if (finalMapCommentCount != null) {
                item.setCommentCount(finalMapCommentCount.get(item.getUid()) == null ? 0 : finalMapCommentCount.get(item.getUid()).size());
            }
            item.setRelation(0);
            //替换用户昵称
            if(item.getArticleSource()==1&& !userMap.isEmpty() &&ObjectUtil.isNotEmpty(item.getUserUid()) && userMap.get(item.getUserUid())!=null){
                String name = userMap.get(item.getUserUid()).getNickName();
                if (StringUtils.isNotEmpty(currentId) && StringUtils.isNotEmpty(finalRemarkMap.get(item.getUserUid()))) {
                    name = finalRemarkMap.get(item.getUserUid());
                }
                item.setUserName(name);
                item.setAuthor(userMap.get(item.getUserUid()).getNickName());
                item.setUserPic(userMap.get(item.getUserUid()).getPic());
                item.setIsHasRealName(CharSequenceUtil.isNotEmpty(userMap.get(item.getUserUid()).getRealName()));
                //添加是否对自己开通私聊
                UserSecurityConfig userSecurityConfig = finalConfigMap.get(item.getUserUid());
                MyFriendVo myFriendVo = finalUserRelations.get(item.getUserUid());
                if(ObjectUtil.isNotNull(userSecurityConfig)&&ObjectUtil.isNotNull(myFriendVo)){
                    item.setIsHasRealName(myFriendVo.getIsHasRealName());
                    item.setMassageSwitch(friendService.getPrivacyTypeValue(Integer.valueOf(myFriendVo.getStatus()),userSecurityConfig.getPrivacyType()));
                    item.setRelation(Integer.parseInt(myFriendVo.getStatus()));
                }
            }
            //设置分类
            if (ObjectUtil.isNotEmpty(item.getBlogSortUid())) {
                item.setBlogSort(blogSortMap.get(item.getBlogSortUid()));
            }
            //获取标签
            if (ObjectUtil.isNotEmpty(item.getTagUid())) {
                List<String> tagUidsTemp = Arrays.asList(item.getTagUid().split(","));
                List<Tag> tagListTemp = new ArrayList<Tag>();
                tagUidsTemp.forEach(tag -> {
                    tagListTemp.add(tagsMap.get(Long.parseLong(tag)));
                });
                item.setTagList(tagListTemp);
            }
            if (StringUtils.isNotBlank(currentId)) {
                // 获取点赞状态
                item.setPraiseIsMe(praiseIsMeMap.get(item.getUid()));
                // 获取收藏状态
                item.setCollectionIsMe(collectionIsMeMap.get(item.getUid()));
            }
            // 获取点赞数量
            item.setPraiseIsMeNum(praiseIsMeNumMap.get(item.getUid()));
            // 获取热评数据
            item.setHotComment(hotCommentMap.get(item.getUid()));

        });
    }

}
